package com.sptpc.controller;

import com.sptpc.domain.Reader;
import com.sptpc.service.UserService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpSession;

@Controller
@RequestMapping("user/")
public class UserController {

	@Autowired
	UserService userService;

	//登录功能
	@RequestMapping("login.do")
	public String login(String id , String password , HttpSession session){
		Reader reader = userService.findUserByIdAndPwd(id , password);
		if (reader != null){
			session.setAttribute("session_reader" , reader);
			return "home";
		}
		return "register" ;
	}

	//退出登陆
	@RequestMapping("back.do")
	public String back(HttpSession session){
		if (session.getAttribute("session_reader") != null){
			session.removeAttribute("session_reader");
			return "redirect:/login";
		}
		return "false";
	}

	//修改用户信息
	@RequestMapping("readerReset.do")
	public String readerReset(String username ,
	                          String dept, String phone,
	                          HttpSession session){
		System.out.println(username+" "+ dept +" " +phone);
		Reader reader = (Reader) session.getAttribute("session_reader");
		reader.setReaderName(username);
		reader.setReaderPhone(Integer.parseInt(phone));
		reader.setReaderDept(dept);
		System.out.println(reader.toString());
		int count = userService.updateAllById(reader);
		if (count > 0){
			return "redirect:/resetList";
		}
		return "false";
	}

	//修改密码
	@RequestMapping("resetPwd.do")
	public String resetPwd(String pass , String newpass ,HttpSession session){
		Reader reader = (Reader) session.getAttribute("session_reader");
		String id = reader.getReaderId();
		int count = userService.updatePwdById(newpass , id , pass);
		System.out.println(reader.toString() + "  " + pass);
		if (count > 0){
			return "true";
		}
		return "false";
	}

	//注册功能
	@RequestMapping("register.do")
	public String register(String userid , String type ,
	                       String username , String password ,
	                       String dept , String phone){
		Reader reader = new Reader();
		reader.setReaderId(userid);
		reader.setReaderName(username);
		reader.setReaderPwd(password);
		reader.setReaderDept(dept);
		reader.setReaderPhone(Integer.parseInt(phone));
		if (type.equals("user")){
			reader.setReaderType("1");
		}else {
			reader.setReaderType("2");
		}
		int count = userService.addReader(reader);
		if (count > 0){
			return "login";
		}
		return "false";
	}

}
